package vip.ola.pay.channel.dszfb;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import vip.ola.core.common.util.MyLog;
import vip.ola.core.common.util.PayDigestUtil;
import vip.ola.core.common.util.PayUtil;
import vip.ola.core.entity.PayOrder;
import vip.ola.core.entity.PayPassageAccount;
import vip.ola.pay.channel.BasePayment;

import java.io.IOException;
import java.util.*;

import static vip.ola.core.common.constant.PayEnum.ERR_0010;
import static vip.ola.core.common.constant.PayEnum.ERR_0121;

@Service
public class DszfbPaymentService extends BasePayment {

    private static final MyLog _log = MyLog.getLog(DszfbPaymentService.class);

    @Override
    public String getChannelName() {
        return null;
    }

    @Override
    public JSONObject pay(PayOrder payOrder) {
        try {
            System.out.println("话费支付使用子账号ID：" + payOrder.getChannelMchId());
            PayPassageAccount payPassageAccount = rpcCommonService.rpcPayPassageAccountService.findById(payOrder.getPassageAccountId());
            if (payPassageAccount == null || StringUtils.isBlank(payPassageAccount.getParam())) {
                return PayUtil.makeRetFail(ERR_0121);
            }
            JSONObject accountParams = JSONObject.parseObject(payPassageAccount.getParam());
            String mchId = payPassageAccount.getPassageMchId();
            String orderId = payOrder.getPayOrderId();
            String reqUrl = accountParams.getString("payUrl");

            Map<String,String> map = new HashMap<>();
            map.put("method",accountParams.getString("method"));
            map.put("sign_type","MD5");
            map.put("login_name",mchId);

            JSONObject obj = new JSONObject();
            obj.put("total_amount",payOrder.getAmount());
            obj.put("out_trade_no",orderId);
            obj.put("notify_url",accountParams.getString("notify_url"));
            map.put("biz_content",obj.toJSONString());
            map.put("sign",getSign(map,payPassageAccount.getPrivateKey()));

            String respData = call(reqUrl,map);
            _log.info("下单返回={}",respData);
            JSONObject resObj = JSON.parseObject(respData);
            if (resObj.getString("code").equals("0000"))
            {
                int result = rpcCommonService.rpcPayOrderService.updateStatus4Ing(payOrder.getPayOrderId(), null);
                String payUrl = resObj.getJSONObject("result").getString("pay_url");
                return PayUtil.makeRetPayUrl(payUrl,null);
            }
            return PayUtil.makeRetFail(ERR_0010);
        }catch (Exception e){
            _log.error(e, "调用话费渠道异常。");
            return PayUtil.makeRetFail(ERR_0010);
        }
    }

    public static String getSign(Map<String,String> param, String signKey){
        SortedMap<String,String> map = new TreeMap<>(param);
        String str = "";
        map.remove("sign");
        for (Map.Entry<String,String> entry : map.entrySet()){
            if (entry.getValue() == null || "".equals(entry.getValue()) || "sign".equals(entry.getKey()))continue;
            str += entry.getValue();
        }
        return PayDigestUtil.md5(str+signKey,"UTF-8");
    }

    public static String getSign(JSONObject param, String signKey){
        SortedMap<String,Object> map = new TreeMap<>(param);
        String str = "";
        map.remove("sign");
        for (Map.Entry<String,Object> entry : map.entrySet()){
            if (entry.getValue() == null || "".equals(entry.getValue()) || "sign".equals(entry.getKey()))continue;
            str += entry.getValue();
        }
        return PayDigestUtil.md5(str+signKey,"UTF-8");
    }

    public static String call(String url, Map param) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        // 响应模型
        CloseableHttpResponse response = null;
        String responseContext = null;
        try {
            StringEntity entity = new StringEntity(JSONObject.toJSONString(param), ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            if (responseEntity != null) {
                responseContext = EntityUtils.toString(responseEntity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContext;
    }

    @Override
    public JSONObject query(PayOrder payOrder) {
        return null;
    }
}
